package uk.ac.cam.bt288.DesktopApp;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Key;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

import biz.source_code.base64Coder.Base64Coder;

public class DesktopApp {

	private static KeyPair keyPair = null;

	private static void loadKeyPair () {
		File keyFile = new File("App.pub");
		if (keyFile.exists()) {
			try {
				keyPair = Keys.readKeyPair("App");
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else {
			keyPair = Keys.GenerateKeyPair();
			try {
				Keys.SaveKey(keyPair, "App");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) throws Exception {

		loadKeyPair();

		System.err.println("Pub key: " + new String(Base64Coder.encode(keyPair.getPublic().getEncoded())));
		QRGenerator.generate(new String(Base64Coder.encode(keyPair.getPublic().getEncoded())) +
				" 60:C5:47:03:62:E7" +
				" 00001101-0000-1000-8000-00805F9B34FA");
		KeyPair client = null;
		client = Keys.readKeyPair("test1");
		Map<Key, String> m = new HashMap<Key,String>();
		m.put(client.getPublic(), "test1");
		ServerSocket serv;
		try {
			serv = new ServerSocket(9999);
			System.out.println("Listening on port 9999");
		} catch (IOException e) {
			System.out.println("Cannot open port 9999");
			return;
		}
		
		while (true) {
			Socket s = null;
			try {
				s = serv.accept();
			} catch (IOException e) {
				e.printStackTrace();
			}
			//launch new ClientHandler for each incoming Pico connection
			ClientHandler c = new ClientHandler(s, keyPair);
			c.authenticate(m);
		}
		

	}

}
